package service

import (
	"VideoManageSystem/internal/initConfig"
	"VideoManageSystem/internal/model"
	"errors"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// CheckDepartmentExist 检查数据库中是否已有该账号
func CheckDepartmentExist(name string) (bool, error) {
	var existingDepartment model.Department
	err := initConfig.GormDb.Where("name = ?", name).First(&existingDepartment).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, nil
		} else {
			// 其他数据库错误
			zap.L().Error("数据库错误，无法检查数据库中是否已有该部门", zap.Error(err))
			return false, err
		}
	} else {
		zap.L().Info("该部门已经被添加", zap.String("部门名称：", name))
		return true, nil
	}
}

// CreateNewDepartment 创建新部门
func CreateNewDepartment(newDepartment model.Department) error {
	err := initConfig.GormDb.Create(&newDepartment).Error
	if err != nil {
		zap.L().Error("无法在数据库中创建新部门", zap.Error(err))
		return err
	}
	return nil
}

// DeleteDepartmentByID 删除部门
func DeleteDepartmentByID(departmentID string) error {
	// 首先，通过 departmentID 获取 departmentName
	var department model.Department
	err := initConfig.GormDb.Where("id = ?", departmentID).First(&department).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			zap.L().Warn("未找到要删除的部门", zap.String("departmentID", departmentID))
			return gorm.ErrRecordNotFound
		}
		zap.L().Error("查询部门信息失败", zap.Error(err))
		return err
	}

	// 检查是否有用户属于该部门
	var userCount int64
	err = initConfig.GormDb.Model(&model.User{}).
		Where("department = ?", department.Name).
		Count(&userCount).Error
	if err != nil {
		zap.L().Error("查询用户数量失败", zap.Error(err))
		return err
	}
	if userCount > 0 {
		zap.L().Warn("无法删除部门，该部门下仍有用户", zap.String("department", department.Name))
		return errors.New("该部门下仍有用户，不能删除")
	}

	// 删除部门
	result := initConfig.GormDb.Where("id = ?", departmentID).Delete(&model.Department{})
	if result.Error != nil {
		zap.L().Error("删除部门失败", zap.Error(result.Error))
		return result.Error
	}

	if result.RowsAffected == 0 {
		zap.L().Warn("未找到要删除的部门", zap.String("departmentID", departmentID))
		return gorm.ErrRecordNotFound
	}

	return nil
}
